﻿using System.Device.Location;
using System.Globalization;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;

namespace SkiTracker.Converter
{
    public class GeoCoordinateJsonConverter : IDataMemberJsonConverter
    {
        public object ConvertFromJson(JToken value)
        {
            var parts = value.ToString().Split(',');

            double latitude;
            double longitude;
            double altitude;

            if (parts.Length == 2)
            {
                if (double.TryParse(parts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out latitude)
                 && double.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out longitude))
                {
                    return new GeoCoordinate(latitude, longitude);
                }
            }
            else if (parts.Length == 3)
            {
                if (double.TryParse(parts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out latitude)
                 && double.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out longitude)
                 && double.TryParse(parts[2], NumberStyles.Any, CultureInfo.InvariantCulture, out altitude))
                {
                    return new GeoCoordinate(latitude, longitude, altitude);
                }
            }
            
            return GeoCoordinate.Unknown;

        }

        public JToken ConvertToJson(object instance)
        {
            var coordinate = instance as GeoCoordinate;
            if (coordinate != null)
            {
                return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2}", coordinate.Latitude, coordinate.Longitude, coordinate.Altitude);
            }
            else
            {
                return "null";
            }
        }
    }
}